package com.zx.flow.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zx.flow.db.entity.FlowConfigEntity;
import com.zx.flow.db.entity.FlowContextEntity;
import com.zx.flow.db.entity.FlowNodeEntity;
import com.zx.flow.db.entity.FlowTraceEntity;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中！
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final String FIELD_CREATE_TIME = "createTime";
    private final String FIELD_UPDATE_TIME = "updateTime";

    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        if (this.autoTable(metaObject)) {
            this.setFieldValByName(FIELD_CREATE_TIME, new Date(), metaObject);
            this.setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
        }
    }

    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        if (this.autoTable(metaObject)) {
            this.setFieldValByName(FIELD_UPDATE_TIME, new Date(), metaObject);
        }
    }

    private boolean autoTable(MetaObject metaObject) {
        return metaObject.getOriginalObject() instanceof FlowConfigEntity
                || metaObject.getOriginalObject() instanceof FlowContextEntity
                || metaObject.getOriginalObject() instanceof FlowNodeEntity
                || metaObject.getOriginalObject() instanceof FlowTraceEntity
                ;
    }
}